package org.example.software.controller;

import org.example.software.exception.MyException;
import org.example.software.service.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.example.software.entity.Forum;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/forum")
public class ForumController {
    @Autowired
    private ForumService forumService;

    // 用户添加留言
    @PostMapping("/add")
    public ResponseEntity<?> addForum(@RequestHeader("Authorization") String token, @RequestBody String content) {
        try {
            boolean success = forumService.addForum(token, content);
            if(success) {
                return ResponseEntity.status(HttpStatus.CREATED).body("用户留言成功");
            }
            else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("用户留言失败");
            }
        } catch (MyException e) {
            // 捕获 MyException，自定义返回状态码和消息
            return ResponseEntity.status(e.getCode()).body(e.getMessage());
        }
        catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }

    // 用户或管理员删除留言
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deleteForum(@RequestHeader("Authorization") String token, @PathVariable int id) {
        try {
            boolean success = forumService.deleteForum(token, id);
            if (success) {
                return ResponseEntity.status(HttpStatus.CREATED).body("留言删除成功");
            }
            else {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("留言删除失败");
            }
        } catch (MyException e) {
            // 捕获 MyException，自定义返回状态码和消息
            return ResponseEntity.status(e.getCode()).body(e.getMessage());
        }
        catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }

}
